import axios from 'axios'
import { removeAllLocalStorage, getAccessToken } from 'utils/auth'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
import { loginOut } from 'api/account'
import { useRouter } from 'vue-router'
import { checkTokenRefresh } from 'utils/util'
// 实例化路由F
const router = useRouter()
// 环境的切换
if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = '/'
} else if (process.env.NODE_ENV === 'debug') {
  axios.defaults.baseURL = '/'
} else if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = '/'
}

// 实例请求服务
const service = axios.create({
  baseURL: axios.defaults.baseURL,
  withCredentials: false,
  timeout: 60000
})

// 请求拦截
service.interceptors.request.use(async(config) => {
  if (config.url === '/api/auth/oauth/token') {
    return config
  }
  // 刷新Token
  await checkTokenRefresh()
  const accessToken = getAccessToken()
  if (accessToken) {
    config.headers['Authorization'] = accessToken
  }
  return config
}, (error) => {
  console.log('request Error', error)
  return Promise.reject('axios' + error)
})

// 响应拦截
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code === 200) {
      return res
    } else if (res.code === 500) {
      showNotify({
        color: '#fff',
        background: '#DE3F2B',
        message: res.msg || '系统异常，请联系管理员'
      })
    } else if (res.code === 3004) {
      showNotify({
        color: '#fff',
        background: '#DE3F2B',
        message: res.msg || 'token已过期'
      })
      // 重新登陆
      loginOut().then(() => {
        removeAllLocalStorage()
        router.push('login')
      })
    } else if (res.code === 10002) {
      showNotify({
        color: '#fff',
        background: '#DE3F2B',
        message: res.msg
      })
    }
    if (response.status === 200) {
      return res
    }
  },
  (error) => {
    if (error?.response?.data) {
      const response = error.response
      const msg = response.data && response.data.msg
      let msgText
      if (response.status === 401) {
        msgText = msg || '尚未登陆,请先登录系统'
        loginOut().then(() => {
          removeAllLocalStorage()
          router.push('login')
        })
      } else if (response.status === 403) {
        msgText = msg || '权限不足'
      } else if (response.status === 404) {
        msgText = msg || '请求不存在'
      } else if (response.status === 413) {
        msgText = msg || '请求体过大'
      } else {
        msgText = msg || '服务器异常，请稍后再试'
      }

      showNotify({
        color: '#fff',
        background: '#DE3F2B',
        message: msgText
      })
    }
    return Promise.reject(error)
  }
)

export default service
